package com.payment.ktb.Fragment;

import android.app.DatePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideTopExit;
import com.flyco.dialog.widget.popup.base.BasePopup;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.main4.OrderManageActivity;
import com.payment.ktb.adapter.AdapterProfitDetail;
import com.payment.ktb.adapter.AdapterProfitSum;
import com.payment.ktb.constants.ConstantsOrderManage;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.model.ProfitDetailEntity;
import com.payment.ktb.model.ProfitSumEntity;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.StringUtils;
import com.payment.ktb.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by admin on 2017/12/5.
 */

public class FragmentProfitManageProfitSum extends BaseFragment implements View.OnClickListener{


    View view;
    TextView tv_fragmentprofitmanageprofitsum_date_starttime;
    TextView tv_fragmentprofitmanageprofitsum_allProfit;
    TextView tv_fragmentprofitmanageprofitsum_date_endtime;
    TextView tv_fragmentprofitmanageprofitsum_status;
    RelativeLayout rl_fragmentprofitmanageprofitsum_date;
    PullToRefreshListView prlv_fragmentprofitmanageprofitsum;

    String ts;
    String te = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    private int page = 0;
    private List<ProfitSumEntity> listDatas = new ArrayList<>();
    private AdapterProfitSum adapter;
    private RelativeLayout rl_fragmentprofitmanageprofitsum_date_all;
    private ImageView iv_fragmentprofitmanageprofitsum_date_arror;
    private RelativeLayout rl_fragmentprofitmanageprofitsum_date_delete;
    private ImageView iv_fragmentprofitmanageprofitsum_status_arror;
    private SimpleCustomPopProfitSumStatus mSimpleCustomPopProfitSumStatus;
    private String stsStatus;
    private RelativeLayout rl_fragmentprofitmanageprofitsum_status;
    private Button btn_fragmentprofitmanageprofitsum_date_confirm;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        view = inflater.inflate(R.layout.fragmentprofitmanageprofitsum,container,false);
        initData();


        return view;


    }

    private void initData() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE,-15);
        ts = new SimpleDateFormat("yyyy-MM").format(new Date()) + "-01";
        mSimpleCustomPopProfitSumStatus = new FragmentProfitManageProfitSum.SimpleCustomPopProfitSumStatus(mContext);
        rl_fragmentprofitmanageprofitsum_date = (RelativeLayout) view.findViewById(R.id.rl_fragmentprofitmanageprofitsum_date);
        rl_fragmentprofitmanageprofitsum_date.setOnClickListener(this);
        btn_fragmentprofitmanageprofitsum_date_confirm = (Button) view.findViewById(R.id.btn_fragmentprofitmanageprofitsum_date_confirm);
        btn_fragmentprofitmanageprofitsum_date_confirm.setOnClickListener(this);
        rl_fragmentprofitmanageprofitsum_date_delete = (RelativeLayout) view.findViewById(R.id.rl_fragmentprofitmanageprofitsum_date_delete);
        rl_fragmentprofitmanageprofitsum_date_delete.setOnClickListener(this);
        rl_fragmentprofitmanageprofitsum_status = (RelativeLayout) view.findViewById(R.id.rl_fragmentprofitmanageprofitsum_status);
        rl_fragmentprofitmanageprofitsum_status.setOnClickListener(this);
        rl_fragmentprofitmanageprofitsum_date_all = (RelativeLayout) view.findViewById(R.id.rl_fragmentprofitmanageprofitsum_date_all);
        iv_fragmentprofitmanageprofitsum_date_arror = (ImageView) view.findViewById(R.id.iv_fragmentprofitmanageprofitsum_date_arror);
        iv_fragmentprofitmanageprofitsum_status_arror = (ImageView) view.findViewById(R.id.iv_fragmentprofitmanageprofitsum_status_arror);
        tv_fragmentprofitmanageprofitsum_date_starttime = (TextView) view.findViewById(R.id.tv_fragmentprofitmanageprofitsum_date_starttime);
        tv_fragmentprofitmanageprofitsum_date_starttime.setOnClickListener(this);
        tv_fragmentprofitmanageprofitsum_date_endtime = (TextView) view.findViewById(R.id.tv_fragmentprofitmanageprofitsum_date_endtime);
        tv_fragmentprofitmanageprofitsum_date_endtime.setOnClickListener(this);
        tv_fragmentprofitmanageprofitsum_allProfit = (TextView) view.findViewById(R.id.tv_fragmentprofitmanageprofitsum_allProfit);
        tv_fragmentprofitmanageprofitsum_status = (TextView) view.findViewById(R.id.tv_fragmentprofitmanageprofitsum_status);
        prlv_fragmentprofitmanageprofitsum = (PullToRefreshListView) view.findViewById(R.id.prlv_fragmentprofitmanageprofitsum);

        // 设置下拉刷新加载文本
        prlv_fragmentprofitmanageprofitsum.getLoadingLayoutProxy(true, false).setPullLabel("下拉刷新...");
        prlv_fragmentprofitmanageprofitsum.getLoadingLayoutProxy(true, false).setReleaseLabel("放开刷新...");
        prlv_fragmentprofitmanageprofitsum.getLoadingLayoutProxy(true, false).setRefreshingLabel("正在加载...");
        // 设置上拉加载文本
        prlv_fragmentprofitmanageprofitsum.getLoadingLayoutProxy(false, true).setPullLabel("上拉刷新...");
        prlv_fragmentprofitmanageprofitsum.getLoadingLayoutProxy(false, true).setReleaseLabel("放开刷新...");
        prlv_fragmentprofitmanageprofitsum.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载...");
        tv_fragmentprofitmanageprofitsum_date_starttime.setText(new SimpleDateFormat("yyyy-MM").format(new Date()) + "-01");
        tv_fragmentprofitmanageprofitsum_date_endtime.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

        prlv_fragmentprofitmanageprofitsum.setMode(PullToRefreshBase.Mode.BOTH);
        prlv_fragmentprofitmanageprofitsum.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //下拉刷新
                pullDownToRefresh();
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pullUptoLoad();


            }
        });
        pullDownToRefresh();

    }


    /**
     *
     */
    private void showStartDateDialog() {

        ToastUtils.showToast("请选择开始时间！");
        new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String time = String.format("%d-%d-%d",year,monthOfYear + 1,dayOfMonth);
                ts = time;
                tv_fragmentprofitmanageprofitsum_date_starttime.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }, Calendar.getInstance().get(Calendar.YEAR),Calendar.getInstance().get(Calendar.MONTH),Calendar.getInstance().get(Calendar.DAY_OF_MONTH)).show();
    }



    /**
     *
     */
    private void showEndDateDialog() {

        ToastUtils.showToast("请选择结束时间！");
        new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                String time = String.format("%d-%d-%d",year,monthOfYear + 1,dayOfMonth);
                te = time;
                tv_fragmentprofitmanageprofitsum_date_endtime.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }, Calendar.getInstance().get(Calendar.YEAR),Calendar.getInstance().get(Calendar.MONTH),Calendar.getInstance().get(Calendar.DAY_OF_MONTH)).show();
    }


    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            //开始时间
            case R.id.tv_fragmentprofitmanageprofitsum_date_starttime:
                showStartDateDialog();
                break;

            //结束时间
            case R.id.tv_fragmentprofitmanageprofitsum_date_endtime:
                showEndDateDialog();
                break;



            //隐藏时间
            case R.id.rl_fragmentprofitmanageprofitsum_date_delete:
                rl_fragmentprofitmanageprofitsum_date_all.setVisibility(View.GONE);
                iv_fragmentprofitmanageprofitsum_date_arror.setImageResource(R.mipmap.order_arror_down);
                break;

            //弹出时间
            case R.id.rl_fragmentprofitmanageprofitsum_date:
                if (rl_fragmentprofitmanageprofitsum_date_all.getVisibility() == View.VISIBLE) {
                    rl_fragmentprofitmanageprofitsum_date_all.setVisibility(View.GONE);
                    iv_fragmentprofitmanageprofitsum_date_arror.setImageResource(R.mipmap.order_arror_down);
                }else {

                    rl_fragmentprofitmanageprofitsum_date_all.setVisibility(View.VISIBLE);
                    iv_fragmentprofitmanageprofitsum_date_arror.setImageResource(R.mipmap.order_arror_up);

                }
                break;




            //时间确认
            case R.id.btn_fragmentprofitmanageprofitsum_date_confirm:
                rl_fragmentprofitmanageprofitsum_date_all.setVisibility(View.GONE);
                iv_fragmentprofitmanageprofitsum_date_arror.setImageResource(R.mipmap.order_arror_down);
                pullDownToRefresh();
                break;






            //类型
            case R.id.rl_fragmentprofitmanageprofitsum_status:


                if (mSimpleCustomPopProfitSumStatus.isShowing()){
                    mSimpleCustomPopProfitSumStatus.dismiss();
                    iv_fragmentprofitmanageprofitsum_status_arror.setImageResource(R.mipmap.order_arror_down);
                }else {
                    mSimpleCustomPopProfitSumStatus
                            .offset(0, 5)
                            .anchorView(rl_fragmentprofitmanageprofitsum_status)
                            .gravity(Gravity.BOTTOM)
                            .showAnim(new BounceTopEnter())
                            .dismissAnim(new SlideTopExit())
                            .dimEnabled(false)
                            .show();
                    iv_fragmentprofitmanageprofitsum_status_arror.setImageResource(R.mipmap.order_arror_up);
                }

                break;


        }
    }






    private void pullDownToRefresh() {

        progressDialogUtils.showProgress();
        //构造传输参数
        page = 0;
        Map<String, String> map = new HashMap<String,String>();
        map.put("ts",ts);
        map.put("te",te);
        map.put("stsStatus",stsStatus);
        map.put("limit", "20");
        map.put("page", String.valueOf(page));
        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.OrgProfitDay, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                try {
                    JSONObject jsonObject = new JSONObject(response);

                    progressDialogUtils.dismissProgress();
                    prlv_fragmentprofitmanageprofitsum.onRefreshComplete();
                    listDatas.clear();
                    tv_fragmentprofitmanageprofitsum_allProfit.setText("¥ " + StringUtils.handleFen2Yuan(jsonObject.optString("allProfit")));
                    //data
                    listDatas = new Gson().fromJson(jsonObject.getJSONArray("records").toString(), new TypeToken<List<ProfitSumEntity>>() {}.getType());
                    if (listDatas == null || listDatas.isEmpty()) {
                        listDatas = new ArrayList<ProfitSumEntity>();
                        ToastUtils.showToast("没有数据！");
                    }
                    //adapter
                    adapter = new AdapterProfitSum(mContext, listDatas);
                    //bind
                    prlv_fragmentprofitmanageprofitsum.setAdapter(adapter);

                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }

            }
            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                prlv_fragmentprofitmanageprofitsum.onRefreshComplete();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });
    }






    private void pullUptoLoad() {

        progressDialogUtils.showProgress();
        //构造传输参数
        page = page + 1;
        Map<String, String> map = new HashMap<String,String>();
        map.put("ts",ts);
        map.put("te",te);
        map.put("stsStatus",stsStatus);
        map.put("limit", "20");
        map.put("page", String.valueOf(page));
        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.OrgProfitDay, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                try {

                    JSONObject jsonObject = new JSONObject(response);

                    progressDialogUtils.dismissProgress();
                    prlv_fragmentprofitmanageprofitsum.onRefreshComplete();
                    //data
                    List<ProfitSumEntity> profitSums = null;
                    profitSums = new Gson().fromJson(jsonObject.getJSONArray("records").toString(), new TypeToken<List<ProfitSumEntity>>() {}.getType());

                    if (profitSums != null && !profitSums.isEmpty()) {
                        //adapter
                        listDatas.addAll(profitSums);
                        adapter.notifyDataSetChanged();
                    }else {
                        ToastUtils.showToast("没有更多数据啦！");
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }

            }
            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                prlv_fragmentprofitmanageprofitsum.onRefreshComplete();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });

    }










    class SimpleCustomPopProfitSumStatus extends BasePopup<SimpleCustomPopProfitSumStatus> {

    RelativeLayout rl_fragmentprofitmanageprofitsum_status_item1;
    TextView tv_fragmentprofitmanageprofitsum_status_item1;
    ImageView iv_fragmentprofitmanageprofitsum_status_item1;
    RelativeLayout rl_fragmentprofitmanageprofitsum_status_item2;
    TextView tv_fragmentprofitmanageprofitsum_status_item2;
    ImageView iv_fragmentprofitmanageprofitsum_status_item2;
    RelativeLayout rl_fragmentprofitmanageprofitsum_status_item3;
    TextView tv_fragmentprofitmanageprofitsum_status_item3;
    ImageView iv_fragmentprofitmanageprofitsum_status_item3;




        public SimpleCustomPopProfitSumStatus(Context context) {
            super(context);
            setCanceledOnTouchOutside(true);
        }

        @Override
        public View onCreatePopupView() {
            View inflate = View.inflate(mContext, R.layout.dialog_fragmentprofitmanageprofitsum_tatus, null);
            rl_fragmentprofitmanageprofitsum_status_item1 = (RelativeLayout) inflate.findViewById(R.id.rl_fragmentprofitmanageprofitsum_status_item1);
            rl_fragmentprofitmanageprofitsum_status_item2 = (RelativeLayout) inflate.findViewById(R.id.rl_fragmentprofitmanageprofitsum_status_item2);
            rl_fragmentprofitmanageprofitsum_status_item3 = (RelativeLayout) inflate.findViewById(R.id.rl_fragmentprofitmanageprofitsum_status_item3);
            tv_fragmentprofitmanageprofitsum_status_item1 = (TextView) inflate.findViewById(R.id.tv_fragmentprofitmanageprofitsum_status_item1);
            tv_fragmentprofitmanageprofitsum_status_item2 = (TextView) inflate.findViewById(R.id.tv_fragmentprofitmanageprofitsum_status_item2);
            tv_fragmentprofitmanageprofitsum_status_item3 = (TextView) inflate.findViewById(R.id.tv_fragmentprofitmanageprofitsum_status_item3);
            iv_fragmentprofitmanageprofitsum_status_item1 = (ImageView) inflate.findViewById(R.id.iv_fragmentprofitmanageprofitsum_status_item1);
            iv_fragmentprofitmanageprofitsum_status_item2 = (ImageView) inflate.findViewById(R.id.iv_fragmentprofitmanageprofitsum_status_item2);
            iv_fragmentprofitmanageprofitsum_status_item3 = (ImageView) inflate.findViewById(R.id.iv_fragmentprofitmanageprofitsum_status_item3);

            return inflate;
        }

        @Override
        public void setUiBeforShow() {
            rl_fragmentprofitmanageprofitsum_status_item1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    iv_fragmentprofitmanageprofitsum_status_item1.setVisibility(View.VISIBLE);
                    iv_fragmentprofitmanageprofitsum_status_item2.setVisibility(View.GONE);
                    iv_fragmentprofitmanageprofitsum_status_item3.setVisibility(View.GONE);
                    mSimpleCustomPopProfitSumStatus.dismiss();
                    iv_fragmentprofitmanageprofitsum_status_arror.setImageResource(R.mipmap.order_arror_down);
                    tv_fragmentprofitmanageprofitsum_status.setText(tv_fragmentprofitmanageprofitsum_status_item1.getText());
                    stsStatus = "";
                    pullDownToRefresh();

                }
            });
            rl_fragmentprofitmanageprofitsum_status_item2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    iv_fragmentprofitmanageprofitsum_status_item2.setVisibility(View.VISIBLE);
                    iv_fragmentprofitmanageprofitsum_status_item1.setVisibility(View.GONE);
                    iv_fragmentprofitmanageprofitsum_status_item3.setVisibility(View.GONE);
                    mSimpleCustomPopProfitSumStatus.dismiss();
                    iv_fragmentprofitmanageprofitsum_status_arror.setImageResource(R.mipmap.order_arror_down);
                    tv_fragmentprofitmanageprofitsum_status.setText(tv_fragmentprofitmanageprofitsum_status_item2.getText());
                    //INIT(0, "未入账")
                    //SUCC(2, "已入账")
                    stsStatus = "2";
                    pullDownToRefresh();
                }
            });
            rl_fragmentprofitmanageprofitsum_status_item3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    iv_fragmentprofitmanageprofitsum_status_item3.setVisibility(View.VISIBLE);
                    iv_fragmentprofitmanageprofitsum_status_item1.setVisibility(View.GONE);
                    iv_fragmentprofitmanageprofitsum_status_item2.setVisibility(View.GONE);
                    mSimpleCustomPopProfitSumStatus.dismiss();
                    iv_fragmentprofitmanageprofitsum_status_arror.setImageResource(R.mipmap.order_arror_down);
                    tv_fragmentprofitmanageprofitsum_status.setText(tv_fragmentprofitmanageprofitsum_status_item3.getText());
                    //INIT(0, "未入账")
                    //SUCC(2, "已入账")
                    stsStatus = "0";
                    pullDownToRefresh();

                }
            });

        }
    }













}
